package com.imist.servlet;

import com.imist.data.LocalCache;
import com.imist.data.Product;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 商品控制器
 */
public class ProductServlet extends HttpServlet {
    @Override
    public void init() throws ServletException {
        super.init();
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setAttribute("products",LocalCache.getProduct());
//        req.getRequestDispatcher("/WEB-INF/views/biz/list.jsp").forward(req,resp);
        String name = req.getParameter("title");

        String pageStr = req.getParameter("page");
        int page = 1;
        if (pageStr != null && !pageStr.equals("")){
            page = Integer.parseInt(pageStr);
        }
        //这里的值要是匹配的值数量和总数都要是匹配的不然下标越界500错误
        int totalProducts = LocalCache.getProductCount(name);

        int totalPage = totalProducts%12 > 0 ?totalProducts/12 +1 :totalProducts/12 ;

        req.setAttribute("curPage",page);
        req.setAttribute("prePage",page > 1 ? page-1 :page);
        req.setAttribute("nextPage",totalPage>page? page+1:totalPage);
        req.setAttribute("totalPage",totalPage);
        req.setAttribute("title",name);

        req.setAttribute("products",LocalCache.getProduct(page,12,name));
        req.getRequestDispatcher("/WEB-INF/views/biz/list.jsp").forward(req,resp);
    }

    @Override
    public void destroy() {
        super.destroy();
    }


}
